﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataLayer.Entities;
using NHibernate.Criterion;

namespace DataLayer.Implementations
{
    public class UserPasswordApplication : GeneralApplication<UserPassword>
    {
        public void Save(UserPassword user)
        {
            if (user.UserPasswordId == null)
            {
                Save(user, 0);
            }
            else
            {
                Save(user, user.UserPasswordId.Value);
            }
        }

        public UserPassword GetByActivationKey(string activationKey)
        {
            List<ICriterion> conditions = new List<ICriterion>();
            conditions.Add(Restrictions.Eq("PasswordApproval", activationKey));

            return model.GetByCriterion<UserPassword>(conditions).FirstOrDefault();
        }

        public UserPassword GetLastByUserId(int userId)
        {
            List<ICriterion> conditions = new List<ICriterion>();
            conditions.Add(Restrictions.Eq("User.UserId", userId));

            IList<UserPassword> list = model.GetByCriterion<UserPassword>(conditions);
            if (list != null && list.Count > 0)
            {
                UserPassword userPass = list.OrderByDescending(x => x.UserPasswordId).FirstOrDefault();
                if (userPass.IsActive)
                {
                    return userPass;
                }
            }
            return null;
        }
    }
}
